import axios from 'axios';

const API_URL = 'http://localhost:8000/api';

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器，添加token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器，处理token过期
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    const originalRequest = error.config;
    
    // 如果是401错误且不是刷新token的请求
    if (error.response.status === 401 && !originalRequest._retry && originalRequest.url !== '/users/token/refresh/') {
      originalRequest._retry = true;
      
      try {
        // 尝试刷新token
        const refreshToken = localStorage.getItem('refreshToken');
        const response = await axios.post(`${API_URL}/users/token/refresh/`, {
          refresh: refreshToken,
        });
        
        // 更新token
        const { access } = response.data;
        localStorage.setItem('token', access);
        
        // 重新发送原始请求
        originalRequest.headers.Authorization = `Bearer ${access}`;
        return apiClient(originalRequest);
      } catch (refreshError) {
        // 刷新token失败，清除本地存储
        // 注意：不要在这里直接跳转，让组件处理错误
        localStorage.removeItem('token');
        localStorage.removeItem('refreshToken');
        // 移除硬跳转，改为抛出错误让组件处理
        return Promise.reject(refreshError);
      }
    }
    
    return Promise.reject(error);
  }
);

// 用户注册
export const register = async (userData) => {
  try {
    const response = await apiClient.post('/users/register/', userData);
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : error;
  }
};

// 检查邮箱是否已存在
export const checkEmail = async (email) => {
  const response = await apiClient.post('/users/check-email/', { email });
  return response.data;
};

// 用户登录
export const login = async (credentials) => {
  try {
    const response = await apiClient.post('/users/login/', credentials);
    // 保存token到本地存储
    localStorage.setItem('token', response.data.access);
    localStorage.setItem('refreshToken', response.data.refresh);
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : error;
  }
};

// 获取当前用户信息
export const getCurrentUser = async () => {
  try {
    const response = await apiClient.get('/users/profile/');
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : error;
  }
};

// 更新用户信息
export const updateUserProfile = async (userData) => {
  try {
    const response = await apiClient.put('/users/profile/', userData);
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : error;
  }
};

// 修改密码
export const changePassword = async (passwordData) => {
  try {
    const response = await apiClient.post('/users/change-password/', passwordData);
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : error;
  }
};

// 登出
export const logout = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('refreshToken');
};

export default apiClient;